local km = vim.keymap

-- 相对行号显示
km.set('n', '<leader>i', function()
    vim.o.rnu = not vim.o.rnu
end, { desc = '切换相对行号显示' })

-- 取消高亮
km.set('n', '<leader>H', function()
    vim.o.hlsearch = false
end, { desc = '取消高亮' })

-- 粘贴板
km.set('n', '<leader>p', [["+p]], { desc = '从系统粘贴板粘贴' })
km.set('x', '<leader>y', [["+y]], { desc = '复制到系统粘贴板' })

-- 在浏览器打开
km.set('n', '<leader>o', function()
    if jit.os == 'Windows' then
        vim.cmd('silent !start msedge file://%:p')
    elseif jit.os == 'OSX' then
        -- 获得用户配置的浏览器
        local handle = io.popen(
        "plutil -p ~/Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist | grep https -b3 | awk 'NR==3 {split($4, arr, \"\\\"\"); print arr[2]}'")
        if handle then
            local bundle = vim.trim(handle:read('*a'))
            handle:close()

            local cmd = 'silent !open -b ' .. bundle .. ' ' .. vim.fn.expand('%:p')
            vim.cmd(cmd)
        end
    else
        vim.cmd('silent !x-www-browser %')
    end
end, { desc = '在浏览器打开当前文件' })

-- 分屏打开光标下的文件
km.set('n', 'gf|', '<cmd>vertical wincmd f<cr>', { desc = '在纵向分屏打开这个文件' })
km.set('n', 'gf_', '<cmd>wincmd f<cr>', { desc = '在横向分屏打开这个文件' })

-- 避免和 tmux 冲突，调整减数字的映射
km.set('n', '<C-s>', '<C-x>', { noremap = true })

-- 切换头文件和源文件
vim.api.nvim_create_autocmd({ 'FileType' }, {
    pattern = { 'cpp', 'c' },
    callback = function()
        km.set('n', '<leader>a', '<cmd>LspClangdSwitchSourceHeader<cr>', { desc = 'Switch cpp source and header file' })
    end
})

-- 切换到当前文件所在的路径
km.set('n', '<leader>ch', function()
    local current_file = vim.fn.expand('%:p')
    if current_file ~= '' then
        local current_dir = vim.fn.expand('%:p:h')
        vim.fn.chdir(current_dir)
    end
end, { desc = '切换工作目录到当前' })
